package com.blds.mc.controller;

import cn.binarywang.wx.miniapp.api.WxMaService;
import cn.binarywang.wx.miniapp.bean.WxMaJscode2SessionResult;
import cn.binarywang.wx.miniapp.bean.WxMaPhoneNumberInfo;
import cn.binarywang.wx.miniapp.bean.WxMaUserInfo;
import com.blds.mc.common.ConstCode;
import com.blds.mc.config.exception.AppException;
import com.blds.mc.entity.User;
import com.blds.mc.service.UserService;
import lombok.extern.slf4j.Slf4j;
import me.chanjar.weixin.common.exception.WxErrorException;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;
import javax.servlet.http.HttpSession;

/**
 * <p>
 * 用户接口
 * </p>
 *
 * @author stwyj
 * @since 2018/6/10
 */
@RestController
@RequestMapping("/wechat/user")
@Slf4j
public class WxMAUserController {

    @Resource
    private WxMaService wxMaService;

    @Resource
    private UserService userService;

    /**
     * 登陆接口
     *
     * @param code 登陆接口code
     * @return 登陆信息sessionId
     */
    @GetMapping("/login")
    public User login(@RequestParam(required = false) String code, HttpSession httpSession) {
        try {
            WxMaJscode2SessionResult session = wxMaService.getUserService().getSessionInfo(code);
            log.info("微信小程序登陆，code为：{}，返回获取的sessionKey为：{}，opernId为：{}", code, session.getSessionKey(), session.getOpenid());

            httpSession.setAttribute(ConstCode.SESSION_KEY_WX_MA_SESSION_KEY, session.getSessionKey());
            httpSession.setAttribute(ConstCode.SESSION_KEY_WX_MA_OPENID, session.getOpenid());
            User user = userService.selectById(session.getOpenid());

            if (user == null) {
                User insertUser = new User();
                insertUser.setOpenId(session.getOpenid());
                userService.insert(insertUser);
                httpSession.setAttribute(ConstCode.SESSION_KEY_USER_INFO, insertUser);
                return insertUser;
            } else {
                httpSession.setAttribute(ConstCode.SESSION_KEY_USER_INFO, user);
                return user;
            }
        } catch (WxErrorException e) {
            log.error("WxMAUserController.login()出错，参数为" + code + "，异常信息为：\n", e);
            throw new AppException("login error", "登录失败", e);
        }
    }

    /**
     * 检测用户session
     *
     * @param httpSession
     * @return
     */
    @GetMapping("checkSession")
    public boolean checkSession(HttpSession httpSession) {
        if (!StringUtils.isEmpty(httpSession.getAttribute(ConstCode.SESSION_KEY_WX_MA_OPENID)) && !StringUtils.isEmpty(ConstCode.SESSION_KEY_WX_MA_SESSION_KEY)) {
            return true;
        } else {
            return false;
        }

    }

    /**
     * 获取用户信息
     *
     * @param sessionKey    会话密钥
     * @param signature     数据签名
     * @param rawData       微信用户基本信息
     * @param encryptedData 消息密文
     * @param iv            加密算法的初始向量
     * @return 用户信息
     */
    @GetMapping("/getUserInfo")
    public WxMaUserInfo getUserInfo(String sessionKey, String signature, String rawData, String encryptedData, String iv) {
        // 用户信息校验
        if (!wxMaService.getUserService().checkUserInfo(sessionKey, rawData, signature)) {
            throw new AppException("user check failed", "获取用户信息检查sessionKey失败");
        }

        // 解密用户信息
        return wxMaService.getUserService().getUserInfo(sessionKey, encryptedData, iv);
    }

    /**
     * 获取用户绑定手机号
     *
     * @param sessionKey    会话密钥
     * @param encryptedData 消息密文
     * @param iv            加密算法的初始向量
     * @return
     */
    @GetMapping("/getUserPhone")
    public WxMaPhoneNumberInfo getUserPhone(String sessionKey, String encryptedData, String iv) {
        // 解密
        return wxMaService.getUserService().getPhoneNoInfo(sessionKey, encryptedData, iv);
    }
}
